import React from 'react';
import {observable, action, computed,toJS} from 'mobx';
import { Tools,SearchBar,Icon,Popover,Toast,Bubble} from 'weaver-mobile';
import { Browser, BrowserHrm,Upload  } from 'weaver-mobile-page';
import * as API from '../../api/goal/goalDetail'
const getLabel = Tools.getLabel;
export default class GoalDetailStore {

    /**
     * 基本信息
     */
    @observable goalId = "" //目标的id
    @observable loading = false; // 页面初始化的loading状态：数据加载成功前后前使用
    @observable detailData ={} //目标详情
    oldDetailData = {};//目标详情暂存值
    @observable cateList = []; //分类详情
    @observable connectGoals = []; //被关联的目标
    @observable connectTasks = []; //被关联的任务
    @observable hasRight = false; //权限
    @observable saveParams = [] //基本信息被修改以后将要保存的值 
    @observable supGoalBrowser = new Browser.Store({ route: '/goalHome/goalDetail' });//上级目标
    @observable principalHrmBrowser = new BrowserHrm.Store({ route: '/goalHome/goalDetail'}); //负责人
    @observable partHrmBrowser = new BrowserHrm.Store({ route: '/goalHome/goalDetail'}); //参与人
    @observable shareHrmBrowser = new BrowserHrm.Store({ route: '/goalHome/goalDetail'}); //分享人
    @observable tagBrowser = new Browser.Store({ route: '/goalHome/goalDetail'}); //标签设置
    @observable canedit = false;
    @observable isOrgGoal = false;
    // @observable realteGoalBrowser = new Browser.Store({ route: '/goalHome/goalAdd' });//相关目标
    // @observable realteTaskBrowser = new Browser.Store({ route: '/goalHome/goalAdd' });//相关任务
    // @observable realteDocBrowser = new Browser.Store({ route: '/goalHome/goalAdd' });//相关文档
    // @observable realteWorkFlowBrowser = new Browser.Store({ route: '/goalHome/goalAdd' });//相关流程
    // @observable realteCustomerBrowser = new Browser.Store({ route: '/goalHome/goalAdd' });//相关客户
    // @observable realteProBrowser = new Browser.Store({ route: '/goalHome/goalAdd' });//相关项目
    // @observable uploadStore = new Upload.Store({ route: '/goalHome/goalAdd' });
    @observable supGoalArray = [];
    @observable principalArray = [];
    @observable partArray = [];
    @observable shareArray = [];
    @observable tagArray = [];


    @observable tabs = [
        { title: getLabel(81711,'基本信息')},
        { title: getLabel(508864,'下级目标')},
        { title: getLabel(383491,'相关信息')},
        { title: getLabel(83596,'反馈信息')},
        { title: getLabel(32061,'操作日志')},
        { title: getLabel(383654, '共享列表')}
    ]
    @observable currpage = 0;  
    @observable showHeadPopover = false

    

    @observable
    changeDetailData = (data) =>{
        this.detailData = data;
    }

    @observable
    changeConnectGoals = (data) =>{
        this.connectGoals = data;
    }

    @observable
    changeConnectTasks = (data) =>{
        this.connectTasks = data;
    }


    /**
     * 获取详细信息
     */
    @action
    getDetailView = (params) =>{
        this.loading = true;
        API.getDetailView(params).then(action(res => {
            if(res.status){
                this.detailData = res.data;
                this.oldDetailData = res.data;
                this.cateList = this.setCateList(res.cateList);
                this.connectGoals = res.connectGoals;
                this.connectTasks = res.connectTasks;
                this.hasRight = res.hasRight;
                this.canedit = res.data.canedit;
                this.isOrgGoal = res.isOrgGoal;
                this.initBrowserValue(res.data);
            }else{
                this.goalId = ""
                this.loading = false;
            }
            this.loading = false;
        }));
    }

    /**
     * 更新目标状态，删除
     */
    @action
    editStatus = (params) =>{
        API.editStatus(params).then(action(res => {
            if(res.status){
                Bubble.success(getLabel(31439,'更新成功'), 1)
                if(typeof params.doback == "function"){
                    params.doback();
                }
            }else{
                Bubble.error( getLabel('25009','失败'), 1)
            } 
        }));
    }

    /**
     * 设置关注信息
     */
    @action
    setSpecial = (params) =>{
        API.setSpecial(params).then(action(res => {
            if(res.status){
                Bubble.success(getLabel(31439,'更新成功'), 1)
                if(typeof params.doback == "function"){
                    params.doback();
                }
            }else{
                Bubble.error( getLabel('25009','失败'), 1)
            }
           
        }));
    }

    @action
    editGoalField = (params) =>{
        API.editGoalField(params).then(action(res => {
            if(res.status){
                Bubble.success(getLabel(31439,'更新成功'), 1)
                this.tagArray = res.tagList;
                if(typeof params.doback == "function"){
                    params.doback();
                }
            }else{
                Bubble.error( getLabel('25009','失败'), 1)
            }
           
        }));
    }

    @action
    setGoalId = (goalId) =>{
        this.goalId = goalId;
    }

    /**
     * 获取浏览按钮的store
     */
    @action
    getBrowserStore = (type) =>{
        if(type == "supGoal"){
            return this.supGoalBrowser;
        }else if(type == "principal"){
            return this.principalHrmBrowser;
        }else if(type == "part"){
            return this.partHrmBrowser;
        }else if(type == "share"){
            return this.shareHrmBrowser;
        }else if(type == "tag"){
            return this.tagBrowser;
        }else{
            return "";
        }
    }

    @action
    setState = (params = {}) => {
        Object.keys(params).forEach((key) => {
            this[key] = params[key];
        });
    }

     /**
     * 设置分类选项
     */
    setCateList = (list)=>{
        let result = [];
        for(let i = 0;i < list.length;i ++){
            let option = {};
            option.key = list[i].id;
            option.showname = list[i].catename;
            result.push(option);
        }
        return result;
    }

    /**
     * 获取右上角的值
     */
    @computed
    get getOverlay(){
        let detailData = this.detailData;
        let itemStyle = {
            minWidth: "80px",
            textAlign:"center"
        }
        let arr = [];
        if(detailData.canedit){
            if(detailData.status == "1"){
                arr = [
                  (<Popover.Item key="1" value={detailData.special == 1 ? "cancelSpecial" : "special"} style={itemStyle}>{detailData.special == 1 ? getLabel(26938,'取消关注') : getLabel(25436,'关注')}</Popover.Item>),
                  (<Popover.Item key="2" value={"complete"} style={itemStyle}>{getLabel(555,'完成')}</Popover.Item>),
                  (<Popover.Item key="5" value={"revoker"} style={itemStyle}>{getLabel(23757,'撤销')}</Popover.Item>),
                  (<Popover.Item key="3" value={"addfb"} style={itemStyle}>{ getLabel(21950,'反馈')}</Popover.Item>),
                ]
              }else{
                arr = [
                  (<Popover.Item key="1" value={detailData.special == 1 ? "cancelSpecial" : "special"} style={itemStyle}>{detailData.special == 1 ? getLabel(26938,'取消关注') : getLabel(25436,'关注')}</Popover.Item>),
                  (<Popover.Item key="2" value={"doing"} style={itemStyle}>{getLabel(382565,'标记进行')}</Popover.Item>),
                  (<Popover.Item key="3" value={"addfb"} style={itemStyle}>{ getLabel(21950,'反馈')}</Popover.Item>),
                  
                ]
              }

        }else{
            arr = [
                (<Popover.Item key="1" value={detailData.special == 1 ? "cancelSpecial" : "special"} style={itemStyle}>{detailData.special == 1 ? getLabel(26938,'取消关注') : getLabel(25436,'关注')}</Popover.Item>),
                (<Popover.Item key="3" value={"addfb"} style={itemStyle}>{ getLabel(21950,'反馈')}</Popover.Item>),
              ]
        }
        if(detailData.canDelete){
            arr.push((<Popover.Item key="4" value={"delete"} style={itemStyle}>{getLabel(91,'删除')}</Popover.Item>));
        }
        return arr;
    }

    /**
     * 设置值
     */
    @action
    setValue = (v,type,btntype) =>{
        if(btntype == "input"){
            this.detailData[type] = v;
            this.changeSaveParams(this.saveParams,{key:type,value:v})
        }else{
            if(type == "parentid"){
                this.supGoalArray = v;
            }else if(type == "principalid"){
                this.principalArray = v;
            }else if(type == "partnerid"){
                this.partArray = v;
            }else if(type == "sharerid"){
                this.shareArray = v;
            }else if(type == "tag"){
                this.tagArray = v;
            }
            this.changeSaveParams(this.saveParams,{key:type,value:this.arrayToString(v)})   
        }
    }

    /**
     * 删除前后没有更改的值
     */
    @action
    deleteNoChangeVlaue = () =>{
        let newData = [];
        let data = this.saveParams;
        let oldData = this.oldDetailData;
        for(let i = 0;i <data.length;i ++){
            if(["parentid","principalid","partnerid","sharerid","tag"].indexOf(data[i].key) > -1){
                let flag = false;
                if(data[i].key == "parentid"){
                    flag = this.judgeIsCanSave(toJS(this.supGoalArray),oldData.parentGoal);
                    this.detailData.parentGoal = toJS(this.supGoalArray);
                }else if(data[i].key == "principalid"){
                    flag = this.judgeIsCanSave(toJS(this.principalArray),oldData.principalid_arr);
                    this.detailData.principalid_arr = toJS(this.principalArray);
                }else if(data[i].key == "partnerid"){
                    flag = this.judgeIsCanSave(toJS(this.partArray),oldData.partnerid_arr);
                    this.detailData.partnerid_arr = toJS(this.partArray);
                }else if(data[i].key == "sharerid"){
                    flag = this.judgeIsCanSave(toJS(this.shareArray),oldData.sharerid_arr);
                    this.detailData.sharerid_arr = toJS(this.shareArray);
                }else if(data[i].key == "tag"){
                    flag = this.judgeIsCanSave(toJS(this.tagArray),oldData.tagArray);
                    this.detailData.tagArray = toJS(this.tagArray);
                }
                if(flag){
                    newData.push(data[i])
                }
            }else{
                if(data[i].value != oldData[data[i].key]){
                    newData.push(data[i]);
                }
            }
        }
       return newData;
    }

    @action
    judgeIsCanSave = (arr1,arr2) =>{
        if(arr1 && arr2){
            if(arr1.length != arr2.length){
                return true;
            }else{
                let newArr1 =[],newArr2 = [];
                for(let i = 0;i < arr1.length;i ++){
                    newArr1.push(arr1[i].id);
                }
                for(let i = 0;i < arr2.length;i ++){
                    newArr2.push(arr2[i].id);
                }
                return newArr1.sort().toString() == newArr2.sort().toString() ? false:true;
            }
        }
        return false;
    }

    @action
    changeSaveParams = (data,value) =>{
        let isAdd = false;
        if(data.length == 0){
            data.push(value);
            return;
        }  
        for(let i = 0;i < data.length;i ++){
            if(data[i].key == value.key){
                data.splice(i,1,value);
                return;
            }
            if(i == data.length - 1){
                isAdd = true;
            }
        }
        if(isAdd){
            data.push(value);
        }
    }

    @action
    arrayToString = (d) =>{
        if(d.length == 1){
            return d[0].id;
        }
        if(d && d.length > 0){
            let str = ",";
            for(let i = 0;i < d.length; i ++){
                str += d[i].id + ",";
            }
            return str;
        }else{
            return "";
        }
    }


    /**
     * 初始化浏览按钮的值
     */
    @action
    initBrowserValue = (obj) =>{
        this.supGoalArray = obj.parentGoal;
        this.principalArray = obj.principalid_arr;
        this.partArray = obj.partnerid_arr;
        this.shareArray = obj.sharerid_arr;
        this.tagArray = obj.tagArray;
    }

    @action
    saveValue = () =>{
        if(this.detailData.name == ""){
            Bubble.warning(getLabel('508796','目标名称不能为空'),1);
            return;
        }
        if(JSON.stringify(this.deleteNoChangeVlaue()) == "[]"){
            Bubble.remind(getLabel(513866, '暂无修改！'), 1)
        }else{
            let params = {saveParams:JSON.stringify(this.deleteNoChangeVlaue()),goalId:this.goalId}
            this.loading = true;
            API.goalSaveBaseInfo(params).then(action(res => {
                if(res.status){
                    if(res.code == 0){
                        Bubble.success(getLabel(31439,'更新成功'), 1)
                        // this.getDetailView({goalId:this.goalId})
                        this.oldDetailData = {...this.detailData}; //重置对比值
                        this.tagArray = res.tagArray;
                    }else if(res.code == 2){
                        Bubble.error(getLabel(521871, '责任人没有创建该组织目标的权限'), 1)
                    }

                }else{
                    Bubble.error( getLabel('25009','失败'), 1)
                }
                this.loading = false;
            }));
        }

        
    }

    @action
    changeCurrpage = (currpage) => {
      this.currpage = currpage
    }

    @action
    changeShowHeadPopover = (showHeadPopover) => {
      this.showHeadPopover = showHeadPopover
    }

    @action
    changeGoalDetailField = (fieldname, fieldvalue) =>{
        this.detailData[fieldname] = fieldvalue
    }

    @observable
    commentReplayAutoFocus = "0"
  
    @action
    changeCommentReplayAutoFocus = (commentReplayAutoFocus) => {
      this.commentReplayAutoFocus = commentReplayAutoFocus
    }
  

}